#redux中间件,处理含有验证的promise
Toast = require('antd-mobile/lib/toast')
{fetchLogOut} = require('../actions/userInfo.js')
_ = require('underscore')
isPromise = (val)->
  val && typeof val.then is 'function'
_fluxStandardAction = require('flux-standard-action')


PromiseMiddleware = ({dispatch,getState})-> (next)-> (action)->
  if _fluxStandardAction.isFSA(action) and isPromise(action.payload) and action.payload?.type is 'token'
    #在这里可以发出一个请求开始的action
    action.payload.then (res)->
      if res.ok
        return res.json()
      else if res.status is 401
        Promise.reject _.extend(new Error('您的账号已在其他设备登陆，请重新登陆。'),{errType:'tokenError'})
      else
        Promise.reject new Error '获取数据错误'
    .then (json)->
      dispatch _.extend({}, action, { payload: json })
    .catch (err)->
      debugger
      Toast.fail(err.message)
      if err.errType is 'tokenError'
        dispatch fetchLogOut()
      dispatch _.extend({}, action, { payload: err, error: true })
  else
    next(action)

module.exports = PromiseMiddleware
